package com.leeyu.rabbitmq.rpc;

import com.leeyu.rabbitmq.util.RabbitMQConnectionUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class Consumer {

    private static final String QUEUE_PUBLISHER = "rpc-publisher";
    private static final String QUEUE_CONSUMER = "rpc-consumer";

    @Test
    public void consume() throws Exception {
        // 获取连接
        Connection connection = RabbitMQConnectionUtil.getConnection();

        // 构建channel
        Channel channel = connection.createChannel();

        // 构建队列
        channel.queueDeclare(QUEUE_PUBLISHER, false, false, false, null);
        channel.queueDeclare(QUEUE_CONSUMER, false, false, false, null);


        // 监听QUEUE_PUBLISHER
        channel.basicConsume(QUEUE_PUBLISHER, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者获取到消息：" + new String(body, StandardCharsets.UTF_8));
                String response = "获取到客户端请求，响应数据：Hello RPC！";
                String responseQueueName = properties.getReplyTo();
                String id = properties.getCorrelationId();
                AMQP.BasicProperties props = new AMQP.BasicProperties()
                        .builder()
                        .correlationId(id)
                        .build();
                channel.basicPublish("", responseQueueName, props, response.getBytes(StandardCharsets.UTF_8));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });

        System.out.println("消息发送成功！");

        System.in.read();
    }
}
